#include "DictVector.h"

#include <iostream>
#include <fstream>
#include <sstream>

using std::cout;
using std::endl;
using std::ifstream;
using std::istringstream;
using std::ostringstream;

Record::Record(const string & word, int frequency)
: _word(word)
, _frequency(frequency)
{}

void Dictionary::read(const string & filename){
    ifstream ifs(filename);
    if(!ifs){
        cout << "file open faid!" << endl;
    }

    string line;
    while(getline(ifs, line)){
        istringstream iss(line);
        string word;
        while(iss >> word){
            //1. 检查字符串
            string newWord = checkWord(word);
            //2. 插入字符串
            insertWord(newWord);
        } 
    }
    ifs.close();
}
string Dictionary::checkWord(string & word){
    for(ssize_t idx = 0; idx != word.size(); ++idx){
        if(!isalpha(word[idx])){
            //字符串有别的符号
            return string();
        }else if(isupper(word[idx])){
            //大写转小写
            word[idx] = tolower(word[idx]);
        }
    }
    return word; 
}
void Dictionary::insertWord(const string & word){
    if(word == string()){
        return;
    }
    ssize_t idx = 0;
    for(; idx != _dict.size(); ++idx){
        if(_dict[idx]._word == word){
            //存在该词
            ++(_dict[idx]._frequency);
            break;
        }
    }
    if(idx == _dict.size()){
        _dict.push_back(Record(word, 1));
    }
}
void Dictionary::store(const string & filename){
    ostringstream oss(filename);
    for(ssize_t idx = 0; idx != _dict.size(); ++idx){
        oss << _dict[idx]._word << "\t\t" << _dict[idx]._frequency << endl;
    }
}